package com.guimin.site.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.guimin.agent.entity.GuiminAgent;
import com.guimin.common.util.exception.BaseException;
import com.guimin.common.vo.R;
import com.guimin.fuwu.entity.GuiminService;
import com.guimin.recycle.entity.GuiminRecycle;
import com.guimin.recycle.service.impl.GuiminRecycleServiceImpl;
import com.guimin.site.entity.GuiminSite;
import com.guimin.site.service.GuiminSiteService;
import com.guimin.site.service.impl.GuiminSiteServiceImpl;
import com.guimin.site.vo.SiteVo;
import com.guimin.user.dto.LoginInfoDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.Size;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * (GuiminSite)表控制层
 *
 * @author makejava
 * @since 2021-11-17 10:11:28
 */
@RestController
@RequestMapping("guiminSite")
public class GuiminSiteController {

    @Resource
    private GuiminSiteServiceImpl siteService;

    /**
     * redis
     */
    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private GuiminRecycleServiceImpl guiminRecycleService;


    public static void main(String[] args) {
        GuiminSiteController guiminSiteController = new GuiminSiteController();
        ArrayList<String> z = guiminSiteController.getDateListByFreeDate("周三");
        System.out.println(z);
    }

    /**
     * 获取当前月周？的号数
     *
     * @param freeDate 传freeDate字段
     * @return
     */
    @GetMapping("/get/date/list")
    public ArrayList<String> getDateListByFreeDate(@RequestParam String freeDate) {
        Calendar calendar = Calendar.getInstance();
        // 获取当前年
        int year = calendar.get(Calendar.YEAR);

        // 获取当前月
        int month = calendar.get(Calendar.MONTH) + 1;

        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy/MM/dd");
        sdf1.setLenient(false);
        SimpleDateFormat sdf2 = new SimpleDateFormat("EEE");
        int toDay = calendar.get(Calendar.DATE);
        ArrayList<String> strings = new ArrayList<>();
        for (int i = 1; i < 32; i++) {
            try {
                Date date = sdf1.parse(year + "/" + month + "/" + i);
                if (sdf2.format(date).equals(freeDate)) {
                    if (i >= toDay) {
                        strings.add(sdf1.format(date) + " : " + sdf2.format(date));
                    }
                }

            } catch (ParseException e) {
                throw new BaseException("获取日期错误");
            }
        }
        return strings;
    }


    /**
     * 获取站点列表
     *
     * @param request
     * @return
     */
    @PostMapping("/list")
    public R<?> getSiteList(HttpServletRequest request) {
        LoginInfoDto userInfo = (LoginInfoDto) redisTemplate.opsForValue().get("token" + request.getHeader("token"));
        List<GuiminSite> siteList = siteService.getSiteList(userInfo.getId());
        if (siteList.size() > 0) {
            return R.success("查询成功", siteList);
        } else {
            return R.fail("查询失败");
        }
    }

    /**
     * 添加站点
     *
     * @param request
     * @param sitevo
     * @return
     */
    @PostMapping("/add")
    public R<?> addSiteData(HttpServletRequest request, @RequestBody SiteVo sitevo) {
        System.out.println(sitevo);
        LoginInfoDto userInfo = (LoginInfoDto) redisTemplate.opsForValue().get("token" + request.getHeader("token"));
        if (sitevo == null) {
            return R.fail("请求参数未空");
        }
        return siteService.addSiteData(userInfo.getId(), sitevo);
    }

    /**
     * 添加站点常规服务
     *
     * @param request
     * @param sites
     * @return
     */
    @PostMapping("/add/cg")
    public R<?> addSiteOrdinaryServe(HttpServletRequest request, @RequestBody SiteVo sites) {
        if (sites.getServeLists().size() == 0) {
            return R.fail("请选择至少一项服务");
        }
        System.out.println("前端请求参数:\n" + sites);
        LoginInfoDto userInfo = (LoginInfoDto) redisTemplate.opsForValue().get("token" + request.getHeader("token"));
        return siteService.addSiteOrdinaryServe(userInfo.getId(), sites);
    }

    /**
     * 添加站点垃圾回收服务
     *
     * @param request
     * @param sites
     * @return
     */
    @PostMapping("/add/laji")
    public R<?> addSiteLaJiServe(HttpServletRequest request, @RequestBody SiteVo sites) {
        if (sites.getRecycleLists().size() == 0) {
            return R.fail("请选择至少一项服务");
        }
        System.out.println("前端请求参数:\n" + sites);
        LoginInfoDto userInfo = (LoginInfoDto) redisTemplate.opsForValue().get("token" + request.getHeader("token"));
        return siteService.addSiteLaJiServe(userInfo.getId(), sites);
    }

    /**
     * 查询站点废旧回收服务
     *
     * @param request
     * @param site
     * @return
     */
    @PostMapping("/list/laji")
    public R<?> detailsSiteData(HttpServletRequest request, @RequestBody GuiminSite site) {
        LoginInfoDto userInfo = (LoginInfoDto) redisTemplate.opsForValue().get("token" + request.getHeader("token"));
        if (site == null) {
            return R.fail("请求参数未空");
        }
        return siteService.detailsSiteData(userInfo.getId(), site);
    }

    /**
     * 查询站点常规服务
     *
     * @param request
     * @param site
     * @return
     */
    @PostMapping("/list/cg")
    public R<?> ordinarySiteData(HttpServletRequest request, @RequestBody GuiminSite site) {
        LoginInfoDto userInfo = (LoginInfoDto) redisTemplate.opsForValue().get("token" + request.getHeader("token"));
        if (site == null) {
            return R.fail("请求参数未空");
        }
        return siteService.ordinarySiteData(userInfo.getId(), site);
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @GetMapping("/delete")
    public R<?> deleteSiteDate(@RequestParam Long id) {
        return siteService.deleteSiteDate(id);
    }

    /**
     * 通过名称删除站点
     *
     * @param name
     * @return
     */
    @GetMapping("/delete/name")
    public R<?> deleteSiteDateByName(@RequestParam String name) {
        return siteService.deleteSiteDateByName(name);
    }


    /**
     * 站点修改
     *
     * @param request
     * @param site
     * @return
     */
    @PostMapping("/revise")
    public R<?> reviseSite(HttpServletRequest request, @RequestBody GuiminSite site) {
        LoginInfoDto userInfo = (LoginInfoDto) redisTemplate.opsForValue().get("token" + request.getHeader("token"));
        return siteService.reviseSite(userInfo.getId(), site);
    }

    /**
     * 批量修改
     *
     * @param sites
     * @return
     */
    @PostMapping("/alter/list")
    public R<?> alterSiteList(@RequestBody List<GuiminSite> sites) {
        System.out.println("前端请求参数\n" + sites);
        if (sites.size() == 0) {
            throw new BaseException("请求参数为空");
        }
        return siteService.alterSiteList(sites);
    }


    /**
     * 根据站点名称和服务类别查找服务
     * 查找某个站点下某个分类的所有服务
     *
     * @param villageName 站点名称
     * @param serveType   服务类别
     * @return
     */
    @GetMapping("/list/by/station")
    public R<List<GuiminSite>> getListBySite(@RequestParam @Size(max = 50) String villageName,
                                             @RequestParam(required = false) @Size(max = 50) String serveType) {
        int count = siteService.count(new LambdaQueryWrapper<GuiminSite>()
                .eq(GuiminSite::getVillageName, villageName)
                .isNotNull(GuiminSite::getRecyclesTwoName));
        if (count == 0) {
            return R.fail(null);
        }
        List<String> recycleArr = null;
        if (StringUtils.isNotBlank(serveType)) {
            //获取分类
            GuiminRecycle recycle = guiminRecycleService.getOne(new LambdaQueryWrapper<GuiminRecycle>()
                    .select(GuiminRecycle::getId).eq(GuiminRecycle::getName, serveType).last("limit 1"));
            if (recycle == null) {
                return R.success(null);
            }
            //根据分类获取服务
            List<GuiminRecycle> recycleList = guiminRecycleService.list(new LambdaQueryWrapper<GuiminRecycle>()
                    .select(GuiminRecycle::getTwoName).eq(GuiminRecycle::getSuperId, recycle.getId()));
            if (recycleList == null || recycleList.size() == 0) {
                return R.success(null);
            }
            recycleArr = recycleList.stream().map(GuiminRecycle::getTwoName).distinct().collect(Collectors.toList());
        }
        //根据服务名称获取站点下的对应服务
        List<GuiminSite> list = siteService.list(new LambdaQueryWrapper<GuiminSite>()
                .select(GuiminSite::getId,GuiminSite::getVillageName,GuiminSite::getRecyclesTwoName,
                        GuiminSite::getVillageProperty,GuiminSite::getRecyclesPrice,GuiminSite::getRecyclesUnit)
                .eq(GuiminSite::getVillageName, villageName)
                .isNotNull(GuiminSite::getRecyclesTwoName)
                .in(StringUtils.isNotBlank(serveType), GuiminSite::getRecyclesTwoName, recycleArr)
        );
        return R.success(null, list);
    }

}

